﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ProxyHero.Common
{
    public class TxtHelper
    {
        public TxtHelper()
        { 
        }

        /// <summary>
        /// 导出代理TXT
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fileName"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string[] WriteProxyTxt(DataTable dt, string fileName, Encoding encode)
        {
            string[] result = {"0",""};
            try
            {
                using (StreamWriter objWriter = new StreamWriter(fileName, false, encode))
                {
                    int i = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        StringBuilder sb = new StringBuilder(dr["IP"].ToString());
                        sb.Append(":");
                        sb.Append(dr["Port"]);
                        sb.Append("@");
                        sb.Append(dr["Type"]);
                        sb.Append("#");
                        sb.Append(dr["Speed"]);
                        sb.Append(" ");
                        sb.Append(dr["Area"]);
                        if (i == dt.Rows.Count - 1)
                        {
                            objWriter.Write(sb.ToString());
                        }
                        else
                        {
                            objWriter.WriteLine(sb.ToString());
                        }
                        i++;
                    }
                }
            }
            catch (Exception ex)
            {
                result[0] = "1";
                result[1] = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 读取所有代理列表TXT
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string[] ReadProxyTxt(string fileName, Encoding encode)
        {
            string[] result = { "0", "" };
            try
            {
                using (StreamReader objReader = new StreamReader(fileName, encode,false))
                {
                    string line;
                    while ((line = objReader.ReadLine()) != null) 
                    {
                        line = line.Trim();
                        Regex regex = new Regex(@"(?<IP>(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))\:(?<Port>\d{1,5})");
                        MatchCollection matchs = regex.Matches(line);
                        if (matchs.Count == 1)
                        {
                            string ip = matchs[0].Groups["IP"].Value;
                            string port = matchs[0].Groups["Port"].Value;
                            // IpHelper ih = new IpHelper(strs[0]);

                            DataRow[] drs = Config.ProxyData.Select("IP='" + ip + "' and Port ='" + port + "'");
                            if (drs.Length == 0)
                            {
                                Config.ProxyData.Rows.Add(new object[] { ip, port, "", "HTTP", "", 99999 });
                            }
                        }
                        //else
                        //{
                        //    result[0] = "1";
                        //    result[1] = line + "数据格式错误！";
                        //    break;
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                result[0] = "1";
                result[1] = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 读取可用代理列表TXT
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string[] ReadAvaliableProxyTxt(string fileName, Encoding encode)
        {
            string[] result = { "0", "" };
            try
            {
                using (StreamReader objReader = new StreamReader(fileName, encode, false))
                {
                    string line;
                    while ((line = objReader.ReadLine()) != null)
                    {
                        line = line.Trim();
                        Regex regex = new Regex(@"(?<IP>(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))\:(?<Port>\d{1,5})");
                        MatchCollection matchs = regex.Matches(line);
                        if (matchs.Count == 1)
                        {
                            string ip = matchs[0].Groups["IP"].Value;
                            string port = matchs[0].Groups["Port"].Value;
                            // IpHelper ih = new IpHelper(strs[0]);

                            DataRow[] drs = Config.AvailableProxyData.Select("IP='" + ip + "' and Port ='" + port + "'");
                            if (drs.Length == 0)
                            {
                                Config.AvailableProxyData.Rows.Add(new object[] { ip, port, "", "HTTP", "", 0 });
                            }
                        }
                        else
                        {
                            result[0] = "1";
                            result[1] = line + "数据格式错误！";
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result[0] = "1";
                result[1] = ex.Message;
            }
            return result;
        }


        public static string[] WriteTxt(string html,string fileName, Encoding encode)
        {
            string[] result = { "0", "" };
            try
            {
                using (StreamWriter objWriter = new StreamWriter(fileName, false, encode))
                {
                    objWriter.Write(html);
                }
            }
            catch (Exception ex)
            {
                result[0] = "1";
                result[1] = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="text"></param>
        public static void WriteLog(string text)
        {
            string fileName = Config.ProxyHeroPath + @"\Log\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            FileInfo fi = new FileInfo(fileName);
            if (!fi.Directory.Exists) fi.Directory.Create();

            //if (!fi.Exists) fi.Create();
            using (StreamWriter objWriter = new StreamWriter(fileName, false, Encoding.UTF8))
            {
                objWriter.WriteLine(DateTime.Now + " " + text);
            }
        }
    }
}
